package com.ilop.sthome.ui.activity.detail.socket;

import android.annotation.SuppressLint;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import com.ilop.sthome.data.enums.DeviceTrigger;
import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.mvp.contract.device.SocketTimingContract;
import com.ilop.sthome.mvp.present.device.SocketTimingPresenter;
import com.ilop.sthome.ui.adapter.device.WeekAdapter;
import com.ilop.sthome.ui.adapter.scene.ChoseActionAdapter;
import com.ilop.sthome.ui.dialog.BaseDialog;
import com.ilop.sthome.ui.dialog.TipDialog;
import com.example.common.view.WheelView;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityTimingEditBinding;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author skygge
 * @date 2020-04-03.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：插座定时编辑
 */
public class SocketTimingActivity extends ContainLoginActivity<SocketTimingPresenter, ActivityTimingEditBinding> implements SocketTimingContract.IView {

    private String mRecommendId;
    private String mDeviceName;
    private int mDeviceId;
    private int mMid;
    private boolean isModify;
    private int mHour;
    private int mMinute;
    private WeekAdapter mWeekAdapter;
    private ChoseActionAdapter mAdapter;
    private ArrayList<String> items_trigger;
    private ArrayList<String> items_code;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_timing_edit;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mRecommendId = getIntent().getStringExtra(CommonId.KEY_RECOMMEND_ID);
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        mDeviceId = getIntent().getIntExtra(CommonId.KEY_DEVICE_ID, -1);
        mMid = getIntent().getIntExtra(CommonId.KEY_AUTOMATION, -1);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new SocketTimingPresenter(mContext, mRecommendId);
    }

    @Override
    protected void initView() {
        super.initView();
        String timer_dw = "(" + getString(R.string.hour_and_min) + ")";
        mDBind.setTimeDw.setText(timer_dw);
        items_trigger = new ArrayList<>();
        items_code = new ArrayList<>();
        mDBind.timerMinute.setCyclic(true);
        mDBind.timerHour.setCyclic(true);
    }

    @Override
    protected void initData() {
        super.initData();
        String deviceType = mPresent.getDeviceInfo(mDeviceName, mDeviceId);
        isModify = mPresent.getAutomationInfo(mMid);
        ArrayList<String> items_hour = mPresent.getHour();
        ArrayList<String> items_min = mPresent.getMinute();
        mDBind.timerHour.setAdapter(new NumberAdapter(items_hour));
        mDBind.timerMinute.setAdapter(new NumberAdapter(items_min));

        int mCode = Objects.requireNonNull(DeviceTrigger.getType(deviceType)).getCode();
        int mTrigger = Objects.requireNonNull(DeviceTrigger.getType(deviceType)).getState();
        items_code.addAll(Arrays.asList(getResources().getStringArray(mCode)));
        items_trigger.addAll(Arrays.asList(getResources().getStringArray(mTrigger)));
        mAdapter = new ChoseActionAdapter(mContext, items_trigger);
        mAdapter.setPosition(0);
        mDBind.socketAction.setLayoutManager(new LinearLayoutManager(mContext));
        mDBind.socketAction.setAdapter(mAdapter);
        mWeekAdapter = new WeekAdapter(mContext, (byte) 0x00);
        mDBind.weekTrigger.setLayoutManager(new GridLayoutManager(mContext, 4));
        mDBind.weekTrigger.setAdapter(mWeekAdapter);
        if (isModify){
            mDBind.timingTitle.setText(getString(R.string.edit_timer));
            mDBind.btTimeDelete.setVisibility(View.VISIBLE);
            String hourAndMin = mPresent.getModifyHourAndMinute();
            mHour = Integer.parseInt(hourAndMin.split(",")[0]);
            mMinute = Integer.parseInt(hourAndMin.split(",")[1]);
            mDBind.timerHour.setCurrentItem(mHour);
            mDBind.timerMinute.setCurrentItem(mMinute);
            HashMap<Integer, Boolean> isSelected = mPresent.getModifyWeekData();
            mWeekAdapter.setIsSelected(isSelected);
            int position = mPresent.getModifySocketState();
            mAdapter.setPosition(position);
        }
        LiveDataBus.get().with(CommonId.CHOOSE_ACTION, Integer.class).observe(this , integer -> mAdapter.setPosition(integer));
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initListener() {
        super.initListener();
        mDBind.timerHour.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                mDBind.timingScroll.requestDisallowInterceptTouchEvent(false);
            }else {
                mDBind.timingScroll.requestDisallowInterceptTouchEvent(true);
            }
            return false;
        });
        mDBind.timerMinute.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                mDBind.timingScroll.requestDisallowInterceptTouchEvent(false);
            }else {
                mDBind.timingScroll.requestDisallowInterceptTouchEvent(true);
            }
            return false;
        });
        mDBind.ivTimingBack.setOnClickListener(view -> whetherToSave());
        mDBind.tvSaveTiming.setOnClickListener(view -> {
            String setting_status = mPresent.getTimerStatus(mWeekAdapter.getIsSelected(), mDBind.timerHour.getCurrentItem(), mDBind.timerMinute.getCurrentItem());
            String action = items_code.get(mAdapter.getPosition());
            mPresent.sendTimingCode(setting_status, action);
            showProgressDialog();
        });

        mDBind.btTimeDelete.setOnClickListener(view -> {
            TipDialog dialog = new TipDialog(mContext, ()->{
                showProgressDialog();
                mPresent.sendDeleteTimer();
            });
            dialog.setMsg(getString(R.string.delete_or_not));
            dialog.show();
        });
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                if (event.getData_str1().length() == 9) {
                    String code = event.getData_str2();
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    if (cmd == SiterCommand.INCREASE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            mPresent.onSendSuccess(false, code.substring(3));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    } else if (cmd == SiterCommand.MODIFY_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            showToast(getString(R.string.modify_successfully));
                            mPresent.onSendSuccess(true, code.substring(3));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    } else if (cmd == SiterCommand.DELETE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            showToast(getString(R.string.delete_success));
                            mPresent.onDeleteSuccess();
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    }
                }
            }
        });
    }

    private void whetherToSave() {
        if (isModify){
            if (mAdapter.getPosition()!= mPresent.getModifySocketState()
                    || mDBind.timerHour.getCurrentItem()!= mHour
                    || mDBind.timerMinute.getCurrentItem()!= mMinute
                    || !mWeekAdapter.getIsSelected().equals(mPresent.getModifyWeekData())){
                showTipDialog();
            }else {
                finish();
            }
        }else {
            if (mAdapter.getPosition()!= 0 || mDBind.timerHour.getCurrentItem()!= 0
                    || mDBind.timerMinute.getCurrentItem()!= 0 || mWeekAdapter.getIsSelected().containsValue(true)){
                showTipDialog();
            }else {
                finish();
            }
        }
    }

    private void showTipDialog(){
        BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                String setting_status = mPresent.getTimerStatus(mWeekAdapter.getIsSelected(), mDBind.timerHour.getCurrentItem(), mDBind.timerMinute.getCurrentItem());
                String action = items_code.get(mAdapter.getPosition());
                mPresent.sendTimingCode(setting_status, action);
                showProgressDialog();
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        mDialog.setMsg(mContext.getString(R.string.save_or_not));
        mDialog.show();
    }

    @Override
    public void showMsg(String msg) {
        showToast(msg);
    }

    @Override
    public void finishActivity() {
        dismissProgressDialog();
        finish();
    }

    private static class NumberAdapter extends WheelView.WheelArrayAdapter<String> {
        NumberAdapter(ArrayList<String> items) {
            super(items);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            whetherToSave();
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
